from artifacts.base.bonus_attr import BonusAttr
from common.random_util import select_one_from_weight_map
import random


class Artifacts:
    SUIT_UNDEFINED = 'UNDEFINED'
    SUIT_A = '套装A'
    SUIT_B = '套装B'

    def get_name(self):
        raise NotImplementedError

    def get_main_attr_weight_map(self):
        raise NotImplementedError

    def get_max_level(self):
        return 20

    def get_level_per_bonus(self):
        return 4

    def creat_bonus_attr(self, exclude=None, attr_type=None):
        return BonusAttr(exclude, attr_type)

    def __init__(self, suit=SUIT_UNDEFINED):
        self.suit = suit
        self.level = 0
        self.bonus_attr_list = []
        self.bonus_data_map = {}
        self.main_attr = select_one_from_weight_map(self.get_main_attr_weight_map())
        self.generate_bonus_attr()

    def __str__(self):
        count_map = {}
        for item in self.bonus_attr_list:
            if item.type in count_map:
                count_map[item.type] += 1
            else:
                count_map[item.type] = 1

        res = f'{self.suit} - {self.get_name()}({self.main_attr[1]})\n'
        for k, v in self.bonus_data_map.items():
            item_str = k[1] + '+'
            if k[2]:
                item_str += str(round(v, 1)) + '%'
            else:
                item_str += str(round(v))
            item_str += f'[{count_map[k]}] '
            res += item_str
        return res

    def generate_bonus_attr(self):
        for i in range(select_one_from_weight_map({3: 80, 4: 20})):
            self._add_new_bonus_attr()

    def upgrade_one_bonus(self):
        self.level += self.get_level_per_bonus()
        if len(self.bonus_attr_list) < 4:
            self._add_new_bonus_attr()
        else:
            self._upgrade_bonus_attr()

    def upgrade_max(self):
        for i in range(int(self.get_max_level() / self.get_level_per_bonus())):
            self.upgrade_one_bonus()

    def _add_new_bonus_attr(self):
        exclude = {self.main_attr}
        for k in self.bonus_data_map:
            exclude.add(k)
        bonus_attr = self.creat_bonus_attr(exclude)
        self.bonus_attr_list.append(bonus_attr)
        self.bonus_data_map[bonus_attr.type] = bonus_attr.data

    def _upgrade_bonus_attr(self):
        attr_type = list(self.bonus_data_map.keys())[random.randint(0, 3)]
        bonus_attr = self.creat_bonus_attr(attr_type=attr_type)
        self.bonus_data_map[attr_type] += bonus_attr.data
        self.bonus_attr_list.append(bonus_attr)
